package com.sms.web.domain.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.sms.client.exception.SendSmsException;
import com.sms.client.utils.AESUtils;
import com.sms.client.utils.SignUtils;
import com.sms.core.request.SmsRequest;
import com.sms.core.service.SendSmsService;
import com.sms.core.utils.SmsUtils;
import com.sms.domain.entity.Application;
import com.sms.domain.service.ApplicationService;
import com.sms.web.rest.RestObject;

/**
 * @desc 以rest方式提供给第其它应用调用短信发送的接口
 * @author WuJiangWu
 * @date 2018年7月21日上午1:12:04
 */
@Controller
@RequestMapping("/api")
public class ApiController {
    
    protected static Logger logger = LoggerFactory.getLogger(ApiController.class);
    
    @Autowired
    private SendSmsService sendSmsService;
    @Autowired
    private ApplicationService applicationService;
    
    /**
     * api短信接口调用
     * @param ssr
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public RestObject send(@RequestParam()boolean isEncrypt, @RequestParam()String text,
    		@RequestParam()String sign, HttpServletRequest request) {
    	
    	//1.检测是否加密，若加密则解密text
        if(isEncrypt){
        	String appId = request.getParameter("appId");
        	if( StringUtils.isBlank(appId) ) {
        		return RestObject.newError("若加密appId要明文传送");
        	}
        	Application  app = applicationService.getOne(appId);
        	//解密  
        	byte[] decryptFrom = AESUtils.parseHexStr2Byte(text);  
        	byte[] decryptResult = AESUtils.decrypt(decryptFrom,app.getSecretKey());  
        	text = new String(decryptResult);
        }
        SmsRequest sr = JSONObject.parseObject(text, SmsRequest.class);
        if(sr==null){
        	return RestObject.newError("json格式异常或加密错误");
        }
        //2.校验签名串
    	if( !SignUtils.checkSign(sign, text) ) {
    		return RestObject.newError("签名字符串和text不匹配");
    	}
        //3.校验参数
        try {
			SmsUtils.validRequest(sr);
		} catch (SendSmsException e) {
			return RestObject.newError(e.getMessage());
		}
        //4.白名单校验...
    	
        try {
            sendSmsService.sendSms(sr);
        } catch (SendSmsException ex) {
            logger.error("短信发送失败，message:{},sms:{}", ex.getMessage(), sr);
            return RestObject.newError(ex.getMessage());
        } catch (Exception ex) {
            logger.error("短信发送失败", ex);
            return RestObject.newError("短信发送失败");
        }
        return RestObject.newOk("success");
    }
    
}
